import { ref } from 'vue'
import { defineStore } from 'pinia'
import { defaultUserInfo, userInfokey, type UserInfo } from '@/config/user/index'
import { getLocal, setLocal } from '@/utils/cache'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserInfo>({})

  const initUserInfo = () => {
    const userInfoStr = getLocal(userInfokey)
    if (userInfoStr) {
      let userInfoObj = {} as UserInfo
      try {
        userInfoObj = JSON.parse(userInfoStr) as UserInfo
        if (userInfoObj) {
          setUserInfo(userInfoObj)
        } else {
          setDefault()
        }
      } catch (e) {
        console.log(e)
        setDefault()
      }
    } else {
      setDefault()
    }
  }
  const setUserInfo = (obj: UserInfo) => {
    userInfo.value = obj
    setLocal(userInfokey, JSON.stringify(obj))
  }
  const setDefault = () => {
    setUserInfo(defaultUserInfo)
  }
  return {
    userInfo,
    initUserInfo,
    setUserInfo,
    setDefault
  }
})
